package com.woniuxueyuan.service.impl;

import com.woniuxueyuan.Producer.DelayProducer;
import com.woniuxueyuan.entity.Order;
import com.woniuxueyuan.entity.OrderItem;
import com.woniuxueyuan.entity.UserCart;
import com.woniuxueyuan.entity.dto.OrderParamDTO;
import com.woniuxueyuan.mapper.OrderMapper;
import com.woniuxueyuan.service.OrderService;
import com.woniuxueyuan.util.ResponseData;
import com.woniuxueyuan.util.SnowflakeIdGenerator;
import com.woniuxueyuan.util.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private DelayProducer delayProducer;
    /**
     * 用户下单接口
     * 1：校验该书籍库存是否足够
     * 2；写入订单表
     * 3：写入订单详情表
     * 4：把购物车书籍状态改成已下单
     * 5：维护书籍的库存量
     * 6.超过15分钟没有付款取消订单
     * @return
     */
    @Override
    public ResponseData<?> addOrder(OrderParamDTO orderParamDTO) throws InterruptedException, ParseException {
        //1：校验该书籍库存是否足够
        List<UserCart> userCarts = orderMapper.checkBookCount(orderParamDTO.getIds());
//        List<String> bookNotEnough = new ArrayList<>();
//        for (UserCart userCart : userCarts) {
//            if(userCart.getBuyNum()>userCart.getStoreCount()){
//                //证明库存不够
//                bookNotEnough.add(userCart.getName());
//            }
//        }
        //集合替换流
        List<String> bookNotEnough = userCarts.stream()
                .filter(e -> e.getBuyNum() > e.getStoreCount())
                .map(e -> e.getName())//映射
                .collect(Collectors.toList());



        if(!CollectionUtils.isEmpty(bookNotEnough)){
            //把库存不足书籍直接返回
            return ResponseData.ok(bookNotEnough);
        }
        //2:写入订单表
        Order order=new Order();
        Integer userId = UserContext.getUserId();
        order.setUserId(userId);
        order.setAddressId(orderParamDTO.getAddrId());
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (UserCart userCart : userCarts) {
            totalPrice =totalPrice.add( userCart.getPrice().multiply(new BigDecimal(userCart.getBuyNum())));

        }
        order.setTotalPrice(totalPrice);
        //获取雪花ID
        SnowflakeIdGenerator sfg = new SnowflakeIdGenerator();
       String orderNum = String.valueOf(sfg.nextId());
        order.setOrderNum(orderNum);//订单编号
        orderMapper.addOrder(order);

        //3:写入订单详情表
        List<OrderItem> orderItems=new ArrayList<>();
        for (UserCart userCart : userCarts) {
            OrderItem orderItem = new OrderItem();
            orderItem.setBookId(userCart.getBookId());
            orderItem.setBookName(userCart.getName());
            orderItem.setOrderId(orderNum);
            orderItem.setBuyCount(userCart.getBuyNum());
            orderItem.setPrice(userCart.getPrice());
            orderItem.setSumPrice(userCart.getPrice().multiply(new BigDecimal(userCart.getBuyNum())));
            orderItems.add(orderItem);
        }
        orderMapper.batchAddOrderItem(orderItems);
        //4：把购物车书籍状态改成已下单
        orderMapper.batchUdateShoppingCartStat(orderParamDTO.getIds());
        //5：维护书籍的库存量
       orderMapper.batchUpdateBookCount(userCarts);
       // 6.超过15分钟没有付款取消订单
        Integer TTL=15*60*1000;
        delayProducer.send(orderNum,"delay",15000);

        return ResponseData.ok();
    }
}
